<template>
  <div :id="uid">
    <el-upload
      :file-list="bufferValue"
      :action="action"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-success="pictureUploadSuccess"
      :on-remove="handleRemove"
      :before-upload="beforeUpload"
      :limit="limit"
      :headers="headers">

      <i class="el-icon-plus"></i>
    </el-upload>
  </div>

</template>

<script>
  import { larkViewer } from 'lark-common'
  import { uploadUrl, getPicUrl } from '@/api/industry/file'
  import { getToken } from '@/utils/auth'
  import { MathUtil } from 'lark-utils'
  //
  export default {
    name: 'picUpload',
    props: {
      prop: {
        type: Object,
        default: () => {
          return {
            name: 'fileName',
            url: 'path'
          }
        }
      },
      value: {
        type: Array,
        default: () => {
          return []
        }
      },
      limit: {
        type: Number,
        default: 100
      }
    },
    model: {
      prop: 'value',
      event: 'changed'
    },
    data() {
      let that = this
      let fl = that.value.map(file => {
        return { name: file[that.prop.name], url: getPicUrl + '/' + file[that.prop.url] }
      })
      return {
        uid: MathUtil.guid(),
        fileList: [],
        action: uploadUrl,
        headers: {
          Authorization: 'Bearer ' + getToken()
        },
        bufferValue: fl
      }
    },
    watch: {
      value: {
        handler(val) {
          let r = document.getElementById(this.uid).querySelector(`.el-upload--picture-card`)
          if (val.length >= this.limit) {
            r.style.display = 'none'
          } else {
            r.style.display = 'block'
          }
          let { fileList } = this
          let that = this

          let bufferFileList = JSON.parse(JSON.stringify(val)).map(file => {
            return { name: file[that.prop.name], url: getPicUrl + '/' + file[that.prop.url] }
          })

          if (fileList !== bufferFileList && JSON.stringify(fileList) !== JSON.stringify(bufferFileList)) {
            this.fileList = bufferFileList
          }
        },
        deep: true
      },
      fileList: {
        handler(newVal) {

          //格式化newVal
          let that = this
          let result = JSON.parse(JSON.stringify(newVal)).map(file => {
            return {
              [that.prop.url]: file['url'].replace(getPicUrl + '/', ''),
              [that.prop.name]: file['name']
            }
          })

          let { value } = this

          if (value !== result && JSON.stringify(value) !== JSON.stringify(result)) {
            this.$emit('changed', result)
          }
        },
        deep: true
      }
    },
    methods: {
      beforeUpload(file) {

        let typeList = ['JPEG', 'JPG', 'TIFF', 'PNG', 'GIF', 'SVG', 'BMP', 'WMV', 'AVI', 'RMVB', 'MP4', 'RM', 'FLV', 'DIVX', 'VOB', 'MKV', 'MPG', 'DAT']

        let lastName = file.name.substring(file.name.lastIndexOf('.') + 1)

        let result = typeList.find(item => item === lastName.toUpperCase())

        if (!result) {
          this.$message({
            message: '请上传图片或者视频',
            type: 'error'
          })
        }

        return result ? true : false
      },
      handleRemove(file, fileList) {
        this.fileList = JSON.parse(JSON.stringify(fileList))
        console.log(file, fileList)
      },
      pictureUploadSuccess(response, file, fileList) {
        this.fileList.push({ name: response.fileName, url: getPicUrl + '/' + response.fileName })
      },
      handlePictureCardPreview(file) {
        larkViewer([{ src: file.url }])
      }
    }
  }
</script>

<style scoped lang="scss">
  .component-upload-image {
    .img-view-root {
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
      flex-wrap: wrap;

      .img-body {
        margin-left: 10px;
        margin-bottom: 10px;
        height: 158px;
        flex: 0 0 158px;
      }
    }
  }

  .avatar {
    width: 100%;
    height: 100%;
  }
</style>
